package jiang.app.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import jiang.app.dao.ICandidateDao;
import jiang.app.entity.Candidate;
import jiang.commom.DateHelper;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class HeadhunterService {

	@Resource
	ICandidateDao candidateDao;

	public boolean saveCandidate(File f) {
		List<Candidate> candidates = resolveExcel(f);
		if (candidates == null) {
			return false;
		}
		boolean success = saveCandidate(candidates);
		return success;
	}

	@Transactional
	public boolean saveCandidate(List<Candidate> list) {
		try {
			for (Candidate c : list) {
				candidateDao.insertCandidate(c);
			}
		}
		catch (Exception e) {
			return false;
		}
		return true;
	}

	public List<Candidate> resolveExcel(File f) {
		List<Candidate> list = new ArrayList<Candidate>();
		try {
			InputStream is = new FileInputStream(f);
			HSSFWorkbook workbook2003 = new HSSFWorkbook(is);// 创建Excel2003文件对象
			HSSFSheet sheet = workbook2003.getSheetAt(0);// 取出第一个工作表，索引是0
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				Candidate c = new Candidate();// 实例化Student对象
				HSSFRow row = sheet.getRow(i);// 获取行对象
				if (row == null) { // 解析完毕
					break;
				}
				// 循环遍历单元格
				HSSFCell name = row.getCell(0);
				HSSFCell phone = row.getCell(1);
				HSSFCell email = row.getCell(2);
				HSSFCell idcard = row.getCell(3);
				HSSFCell money = row.getCell(4);
				HSSFCell city = row.getCell(5);
				HSSFCell birthday = row.getCell(6);
				HSSFCell job = row.getCell(7);
				if (name == null || idcard == null) {
					continue;
				}
				c.setName(name.getStringCellValue());
				c.setPhone(phone.getStringCellValue());
				c.setEmail(email.getStringCellValue());
				c.setIDCardNumber(idcard.getStringCellValue());
				c.setMoney((int) money.getNumericCellValue());
				c.setCity(city.getStringCellValue());
				c.setBirthday(birthday.getStringCellValue());
				c.setJob(job.getStringCellValue());
				c.setRegisterTime(DateHelper.getCurrentDate());
				list.add(c);// 数据装入List
			}
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return list;
	}
}
